<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ include file="../config/config.jsp"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page
	import="java.util.*,com.cinema.Bean.*,com.cinema.dao.*,com.cinema.dao.imp.*"%>
<%@ page import="java.io.*,java.util.*"%>
<%@ page import="javax.servlet.*,java.text.*"%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>选座购票</title>
<link rel="stylesheet" href="<%=basePath%>/css/bootstrap.min.css" />
<link rel="stylesheet" href="<%=basePath%>/css/bootstrap-theme.min.css" />
<link rel="stylesheet" href="<%=basePath%>/css/index.css" />
<link rel="stylesheet" href="<%=basePath%>/css/seates.css?v=12" />
<script type="text/javascript" src="<%=basePath%>js/jquery-3.2.1.min.js"></script>
<script src="<%=basePath%>js/bootstrap.min.js"></script>

</head>
<body>
	<!--头部导航-->
	<nav class="navbar navbar-default navbar-fixed-top nav-min-height">
		<div class="container">
			<div class="navbar-header nav-min-height">
				<a href="#" class="navbar-brand logo"><img
					src="<%=basePath%>/images/logo.png" alt=""></a>
				<button type="button" class="navbar-toggle" data-toggle="collapse"
					data-target="#navbar-collapse">
					<span class="icon-bar"></span> <span class="icon-bar"></span> <span
						class="icon-bar"></span>
				</button>
			</div>
			<div class="collapse navbar-collapse  nav-min-height"
				id="navbar-collapse">
				<ul class="nav navbar-nav navbar-right  nav-min-height">
					<li class="active"><a href="<%=basePath%>/indexServlet"><span
							class="glyphicon glyphicon-home"></span> 首页</a></li>
					<li><a href="<%=basePath%>ticketServlet?method=selectByUser&userId=${sessionScope.loginUser.userId}"> 
						<span class="glyphicon glyphicon-user"></span>
							${sessionScope.loginUser.userName}
						</a>
					</li>
				</ul>
			</div>
		</div>
	</nav>

	<div class="container container_seat">
		<div class="content_box">
			<!---左边座位列表----->
			<div class="seat_area">
				<div class="front">屏幕</div>
				<div class="weizi" id="weizi">
					<%
						List<Seats> seats = (List<Seats>) request.getAttribute("seatsList");
						List<Ticket> usedSeats = (List<Ticket>) request.getAttribute("usedSeatsList");
						for (int i = 0; i < seats.size(); i++) {//所有行，从0开始
					%>
					<p class="hang">
						<%
							for (int m = 0; m < seats.get(i).getSeatCount(); m++) {//每一行座位数
						%>
						<span onClick="getSeatMes(this,<%=i + 1%>,<%=m + 1%>);"
							class="normal-span myspan-<%=i + 1%><%=m + 1%>"><%=i + 1%>-<%=m + 1%></span>
						<%
							for (int n = 0; n < usedSeats.size(); n++) {
										if (i == (usedSeats.get(n).getSeatRow() - 1) && m == (usedSeats.get(n).getSeatCol() - 1)) {
						%>
						<script type="text/javascript">
								var $span=$(".myspan-<%=i + 1%><%=m + 1%>");
								$span.removeAttr("onclick");
								$span.removeClass("normal-span");
								$span.css({"background-color":"#472B34","disabled":"disabled","cursor":"not-allowed"});
						</script>
						
						<%
							}
									}
								}
						%>
					</p>
					<%
						}
					%>
				</div>
			</div>
			<%
				List<Map<String, Object>> movieMessage = (List<Map<String, Object>>) request.getAttribute("movieMessage");
				for (int i = 0; i < movieMessage.size(); i++) {
					Map<String, Object> obj = movieMessage.get(i);
					MovieSession ms = (MovieSession) obj.get("movieSession");
					Hall hall = (Hall) obj.get("hall");
					Movie movie = (Movie) obj.get("movie");
					SimpleDateFormat ftDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					String time = ftDateTime.format(ftDateTime.parse(ms.getTime()));
			%>
			<!---右边选座信息----->
			<div class="booking_area">
				<h2 class=title><%=movie.getMovieName()%></h2>
				<p>
					影厅：<span><%=hall.getHallName()%></span>
				</p>
				<p>
					时间：<span><%=time%></span>
				</p>
				<p>
					单价：￥<span id="singleprice"><%=ms.getPrice()%></span>
				</p>
				<%
					}
				%>
				<p id="zuowei">座位：</p>
				<ul id="selected-seats"></ul>
				<p>
					票数：<span id="tickects_num">0</span>
				</p>
				<p>
					总价：<b>￥<span id="total_price">0</span></b>
				</p>
				<button type="button" class="bought" id="bookNowBtn"
					data-toggle="modal" data-target="#sureBuyModal" value="确定购买">确认购买</button>
				<div id="legend" class="legend">
					<ul class="legendList">
						<li class="legendItem"><div class="seat cell available"></div>
							<span class="legendDescription">可选座</span></li>
						<li class="legendItem"><div class="seat cell unavailable"></div>
							<span class="legendDescription">已售出</span></li>
					</ul>

				</div>
			</div>
		</div>
	</div>

	<!-- 确认购买模态框 -->
	<div class="modal fade" id="sureBuyModal" data-backdrop="static">
		<div class="modal-dialog">
			<div class="modal-content message_align">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title">提示信息</h4>
				</div>
				<div class="modal-body">
					<p>您确认购买吗？</p>
				</div>
				<div class="modal-footer">
					<input type="hidden" id="url" />
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<a onclick="sureBuy();" class="btn btn-success" data-dismiss="modal">确定</a>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->

	<script>

var row=0; // 座位行号（默认0）
var col=0; // 座位列号（默认0）
var flag = true; // 默认票数小于2	
var price = parseInt($("#singleprice").text()); // 单价

/**
 * 计算票价总额
 */
function getTotalPrice(sc) {
	 var total = 0;
     sc.find('selected').each(function() {
         total += price;
     });
     return total;
}

/**
 * 获取用户信息
 */
function getSeatMes(obj,i,j){
	var selec = $(obj).hasClass('selectBg');// 已经选择的座位
	if(selec) {
		flag = true;
	}
	if(flag) {
		if($(obj).hasClass('selectBg')){//位置已经被购买了
			//座位号为默认
			row=0;
			col=0;
			$(obj).removeClass('selectBg');
			$(obj).css('backgroundColor','#B9DEA0');
			$("li:contains('" + $(obj).text() + "')").remove();
			var ccon = parseInt($("#tickects_num").text());
			$("#tickects_num").text((ccon - 1).toString());
			var tprice = parseInt($("#total_price").text());
			$("#total_price").text((tprice - price).toString());
			
		}else{//没选，可以购买的位置
			row=row+","+i;//i，j前面传过来的
			col=col+","+j;
			
			$(obj).addClass('selectBg');
			$(obj).css('backgroundColor','gray');
			$('<li>' + obj.innerText + '</li>').appendTo("#selected-seats");
			var ccon = parseInt($("#tickects_num").text());
			$("#tickects_num").text((ccon + 1).toString());
			var tprice = parseInt($("#total_price").text());
			$("#total_price").text((tprice + price).toString());
		}
	}
	
	// 得到票数
	var ccon = parseInt($("#tickects_num").text());
	//单次购票不超过2张
	if(ccon > 1){
		flag = false;
	}else{
		//添加点击事件
		flag = true;
	}
}

/**
 * 确认购买
 */
function sureBuy(){
	var totalPrice=$("#total_price").text();
	//1.判断是否登录
	if("${not empty sessionScope.loginUser.userId}"){
		 var money = getBalance();
		 
		 if(money < totalPrice){
			alert("余额不足！请充值");
			//$("#userBalanceModal").modal('show');
			
		 }else{
			 var id="${sessionScope.loginUser.userId}";
			 var url = "<%=basePath%>userServlet";
			 var args={"userId":id,"method":"getBalanInfo","time":new Date()};
			 // 获取用户余额
			 var balanMoney = 0;
		     $.ajax({
		    	 url: url,
			     async: false, // 同步
			     type: 'POST',
			     dataType : "json", // 传回的数据格式
		　　　　    data: args,
		　　　　　   //请求成功后触发
		　　　　　   success: function (data) { 
			   		balanMoney = data.balance;
		　　　　　   },
		         error: function(data) {
		        	alert('获取失败！'); 
		         }
		     });
		     
		     // 修改用户余额
		     var balance = balanMoney - totalPrice;
		    
		     var params={"userId":id,"method":"updateBalance","balance":balance,"time":new Date()};
		     $.ajax({
		    	 url: url,
		　　　　　  type: 'POST',
			     async: false, // 同步
			     dataType : "json", // 传回的数据格式
		　　　　　   data: params,
		　　　　　   //请求成功后触发
		　　　　　   success: function (data) { 
			   		if("success"==data){
			           alert('扣款成功！');
			        }else if("error"==data){
			           alert('扣款失败，请联系管理员！'); 
			        }
		　　　　　   }
		     });
		     
		     console.log(row,col);
			// 锁定座位	
			var sessionId='${sessionId}';
			 $.ajax({
			    url: "<%=basePath%>seatsServlet",
		　　　　   type: 'POST',
			    async: false, // 同步
		　　　　　  data: { method: "buyTicket",seatRow:row,seatCol:col,sessionId:"${sessionId}",userId:"${sessionScope.loginUser.userId}",totalPrice:totalPrice},		　　　　
	
		       //请求成功后触发
		　　　　　 success: function (data) { 
					alert("购买成功！");
					window.location.href="<%=basePath%>seatsServlet?method=initTicketData&sessionId="+sessionId;
		　　　　　 },
		　　　　　 //请求失败遇到异常触发
		　　　　　 error: function (data) {
			 		alert("购买失败，请联系管理员！");
		　　　　　 }
	　　　　	});
		 }
	}else{
		alert("请先登录！");
	}
}

// 用户余额充值
$("#minusBtn").click(function() {  // 减号
	var balance = ($("#balance").val())*1;
	if(balance > 5) {
		$("#balance").val(balance-5);
	}
});
$("#plusBtn").click(function() { // 加号
	var balance = ($("#balance").val())*1;
	$("#balance").val(balance+5);
});

/**
 * 从数据库中获取用户余额
 * @return 余额money
 */
function getBalance() {
	var money = null;
	//2.查询余额
	var id="${sessionScope.loginUser.userId}";
	var url = "<%=basePath%>userServlet";
	var args={"userId":id,"method":"getBalanInfo","time":new Date()};
    
    $.ajax({
    	type: "post",
        url: url,
        data: args,
        async : false,
        dataType: "json",
        success: function (data){
        	money = data.balance;
        }
    });
    return money;
}
	
</script>

</body>
</html>